﻿// owner 蒋家伟

#include "ExcelWriter.h"

// jsdk
#include "Dbg_Warn_Define.h"
#include "StringUtils.h"

using namespace jsdk;

OwnerPtr<jsdk::ExcelWriter> jsdk::ExcelWriter::create(const std::wstring& fileName)
{
    OwnerPtr<jsdk::ExcelWriter> opExcel = NEW_AS_OWNERPTR(ExcelWriter);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(opExcel, L"Excel对象创建失败", L"蒋家伟", L"2023-09-15");
    opExcel->m_fileName = fileName;
    opExcel->m_workSheet = opExcel->m_workBook.active_sheet();
    return std::move(opExcel);
}

jsdk::ExcelWriter::~ExcelWriter()
{
}

uint64_t jsdk::ExcelWriter::addSheet(const std::wstring& sheetName)
{
    xlnt::worksheet worksheet = m_workBook.create_sheet();
    worksheet.title(StringUtils::toString(sheetName));
    return m_workBook.sheet_count() - 1;
}

bool jsdk::ExcelWriter::openSheet(uint32_t sheetIndex)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(sheetIndex < m_workBook.sheet_count(), L"index 越界， 当前excel没有对应index的sheet。 Index ： " + StringUtils::toWString(sheetIndex) , L"蒋家伟", L"2023-09-25");
    m_workSheet = m_workBook.sheet_by_index(sheetIndex);
    return true;
}

bool jsdk::ExcelWriter::setCellData(uint32_t row, uint32_t col, const std::wstring& valueStr)
{
    std::string str = StringUtils::toUTF8String(valueStr);
    m_workSheet.cell(col, row).value(str.c_str());
    return true;
}

bool jsdk::ExcelWriter::deleteSheet(const std::wstring& sheetName)
{
    if (m_workBook.sheet_count())
        return false;
    xlnt::worksheet worksheet =  m_workBook.sheet_by_title(StringUtils::toString(sheetName));
    m_workBook.remove_sheet(worksheet);
    return true;
}

bool jsdk::ExcelWriter::save() const
{
#ifdef _MSC_VER
    try
    {
        m_workBook.save(m_fileName);
    }
    catch (xlnt::exception excption)
    {
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(false, StringUtils::toWString(excption.what()), L"蒋家伟", L"2023-10-23");
    }
#elif
    try
    {
        m_workBook.save(StringUtils::toString(m_fileName));
    }
    catch (xlnt::exception excption)
    {
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(false, StringUtils::toWString(excption.what()), L"蒋家伟", L"2023-10-23");
    }
#endif
    return true;
}
